package com.jacky.ws.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ChannelSupervise {

    private static final ChannelGroup GLOBAL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final ConcurrentMap<String, ChannelId> channelMap = new ConcurrentHashMap<>();

    public static void addChannel(Channel channel) {
        GLOBAL_GROUP.add(channel);
        channelMap.put(channel.id().asShortText(), channel.id());
    }

    public static void removeChannel(Channel channel) {
        GLOBAL_GROUP.remove(channel);
        channelMap.remove(channel.id().asShortText());
    }

    public static Channel findChannel(String id) {
        return GLOBAL_GROUP.find(channelMap.get(id));
    }

    public static void send2All(TextWebSocketFrame frame) {
        GLOBAL_GROUP.writeAndFlush(frame);
    }

    public static void send2Others(TextWebSocketFrame frame, Channel currentChannel) {
        GLOBAL_GROUP.writeAndFlush(frame, new ChannelMatcher() {
            @Override
            public boolean matches(Channel channel) {
                return !channel.equals(currentChannel);
            }
        });
    }
}
